<template>
  <el-drawer v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" size="100%" :title="`${drawerProps.title}`">
    <template v-if="!drawerProps.isView">
      <div class="content">
        <div class="questionSelList">
          <ProTable
            ref="questionSelTable"
            title="试题选择列表"
            rowKey="questionId"
            :columns="columns"
            :request-api="getTableList"
            :init-param="initParam"
            :data-callback="dataCallback"
            @selection-change="_getSelList"
          >
            <template #expand="scope">
              {{ scope.row }}
            </template>
          </ProTable>
        </div>
        <div class="splitLine"></div>
        <div class="paperForm">
          <el-form
            ref="examPaperFormRef"
            label-width="100px"
            label-suffix=" :"
            :rules="rules"
            :disabled="drawerProps.isView"
            :model="drawerProps.row"
            :hide-required-asterisk="drawerProps.isView"
          >
            <el-form-item label="试卷名称" prop="paperName">
              <el-input v-model="drawerProps.row!.paperName" placeholder="请填写试卷名称" clearable></el-input>
            </el-form-item>
          </el-form>
          <div class="questionList" v-if="singleSelectionQuestionList.length">
            <div class="questionTitle">
              <span class="questionTitle__text">单选题</span><span class="clearBtn" @click="_clearQuestion(1)">清空</span>
            </div>
            <div class="questionItemWrap" v-for="(item, index) in singleSelectionQuestionList" :key="item.questionId">
              <div class="questionItem">
                <span class="questionNo">{{ index + 1 }}.</span>
                <el-tooltip class="box-item" effect="dark" :content="item.questionStem" placement="top-start">
                  <div class="questionName">{{ item.questionStem }}</div>
                </el-tooltip>
                <el-input class="questionScore" size="small" v-model="item.questionScore">
                  <template #suffix><span>分</span></template>
                </el-input>
                <el-icon class="delBtn" color="var(--el-color-error)" @click="_delQuestionItem(1, index)"><Delete /></el-icon>
              </div>
              <div class="answerOpts">
                <div class="answerItemWrap" v-for="val in item.optionList" :key="val.optionCode">
                  <div class="answerItem" v-if="val.optionCode">{{ val.optionCode }}、{{ val.optionContent }}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="questionList" v-if="moreSelectionQuestionList.length">
            <div class="questionTitle">
              <span class="questionTitle__text">多选题</span><span class="clearBtn" @click="_clearQuestion(2)">清空</span>
            </div>
            <div class="questionItemWrap" v-for="(item, index) in moreSelectionQuestionList" :key="item.questionId">
              <div class="questionItem">
                <span class="questionNo">{{ index + 1 }}.</span>
                <el-tooltip class="box-item" effect="dark" :content="item.questionStem" placement="top-start">
                  <div class="questionName">{{ item.questionStem }}</div>
                </el-tooltip>
                <el-input class="questionScore" size="small" v-model="item.questionScore">
                  <template #suffix><span>分</span></template>
                </el-input>
                <el-icon class="delBtn" color="var(--el-color-error)" @click="_delQuestionItem(2, index)"><Delete /></el-icon>
              </div>
              <div class="answerOpts">
                <div class="answerItemWrap" v-for="val in item.optionList" :key="val.optionCode">
                  <div class="answerItem" v-if="val.optionCode">{{ val.optionCode }}、{{ val.optionContent }}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="questionList" v-if="tfQuestionList.length">
            <div class="questionTitle">
              <span class="questionTitle__text">判断题</span><span class="clearBtn" @click="_clearQuestion(3)">清空</span>
            </div>
            <div class="questionItem" v-for="(item, index) in tfQuestionList" :key="item.questionId">
              <span class="questionNo">{{ index + 1 }}.</span>
              <el-tooltip class="box-item" effect="dark" :content="item.questionStem" placement="top-start">
                <div class="questionName">{{ item.questionStem }}</div>
              </el-tooltip>
              <el-input class="questionScore" size="small" v-model="item.questionScore">
                <template #suffix><span>分</span></template>
              </el-input>
              <el-icon class="delBtn" color="var(--el-color-error)" @click="_delQuestionItem(3, index)"><Delete /></el-icon>
            </div>
          </div>
          <div class="questionList" v-if="completionQuestionList.length">
            <div class="questionTitle">
              <span class="questionTitle__text">填空题</span><span class="clearBtn" @click="_clearQuestion(4)">清空</span>
            </div>
            <div class="questionItem" v-for="(item, index) in completionQuestionList" :key="item.questionId">
              <span class="questionNo">{{ index + 1 }}.</span>
              <el-tooltip class="box-item" effect="dark" :content="item.questionStem" placement="top-start">
                <div class="questionName">{{ item.questionStem }}</div>
              </el-tooltip>
              <el-input class="questionScore" size="small" v-model="item.questionScore">
                <template #suffix><span>分</span></template>
              </el-input>
              <el-icon class="delBtn" color="var(--el-color-error)" @click="_delQuestionItem(4, index)"><Delete /></el-icon>
            </div>
          </div>
          <div class="questionList" v-if="qaQuestionList.length">
            <div class="questionTitle">
              <span class="questionTitle__text">问答题</span><span class="clearBtn" @click="_clearQuestion(5)">清空</span>
            </div>
            <div class="questionItem" v-for="(item, index) in qaQuestionList" :key="item.questionId">
              <span class="questionNo">{{ index + 1 }}.</span>
              <el-tooltip class="box-item" effect="dark" :content="item.questionStem" placement="top-start">
                <div class="questionName">{{ item.questionStem }}</div>
              </el-tooltip>
              <el-input class="questionScore" size="small" v-model="item.questionScore">
                <template #suffix><span>分</span></template>
              </el-input>
              <el-icon class="delBtn" color="var(--el-color-error)" @click="_delQuestionItem(5, index)"><Delete /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </template>
    <template v-else>
      <div id="printDiv">
        <div class="header">
          <div class="examTitle">{{ drawerProps.row!.paperName }}</div>
          <!-- <div class="examSubTitle">
          <div class="examSubTitle__item">
            <span class="examSubTitle__item__lab">考试时长：</span>
            <span class="examSubTitle__item__text">{{ examDuration }}</span>
            <span class="examSubTitle__item__unit">分钟</span>
          </div>
          <div class="examSubTitle__item">
            <span class="examSubTitle__item__lab">监考老师：</span>
            <span class="examSubTitle__item__text">{{ testSelfDtl.teacherName }}</span>
          </div>
        </div> -->
        </div>
        <div class="testPart">
          <div class="testPaper">
            <div class="testList" v-for="(item, index) in questionList" :key="index">
              <div class="testTypeTitle">{{ `${questionTypeCnNo[index]}、${item.label}` }}</div>
              <div class="testItem" v-for="(val, idx) in item.value" :key="val.questionId">
                <div class="testName">{{ `${idx + 1}、 ${val.questionStem} （${val.questionScore}分）` }}</div>
                <div class="testAnswer">
                  <div v-if="item.label === '单选题'">
                    <div class="answerContent">
                      <div v-for="v in val.optionList" :key="v.optionCode">
                        <div class="answerItem" v-if="v.optionCode">{{ `${v.optionCode}、${v.optionContent}` }}</div>
                      </div>
                    </div>
                  </div>
                  <div v-if="item.label === '多选题'">
                    <div class="answerContent">
                      <div v-for="v in val.optionList" :key="v.optionCode">
                        <div class="answerItem" v-if="v.optionCode">{{ `${v.optionCode}、${v.optionContent}` }}</div>
                      </div>
                    </div>
                  </div>
                  <div v-if="item.label === '判断题'">
                    <div class="answerContent">
                      <div class="answerItem"><span class="checkBox"></span><span>正确</span></div>
                      <div class="answerItem"><span class="checkBox"></span><span>错误</span></div>
                    </div>
                  </div>
                  <div v-if="item.label === '填空题'">
                    <div class="answerContent answerContent1">答：</div>
                  </div>
                  <div v-if="item.label === '问答题'">
                    <div class="answerContent answerContent2">答：</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>

    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
      <el-button
        type="primary"
        v-print="{ popTitle: '', preview: false, zIndex: 20002, id: 'printDiv' }"
        v-if="drawerProps.isView"
      >
        打印
      </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="tsx" name="ExamPaperDrawer">
import { ref, reactive, nextTick, watch } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { ExamPaper, ExamQuestion, ResultData } from "@/api/interface";
import { ColumnProps } from "@/components/ProTable/interface";
import ProTable from "@/components/ProTable/index.vue";

import { questionType } from "@/utils/serviceDict";
import { getExamPaperDtl } from "@/api/modules/examManage/examPaper";
import { getExamQuestionSelList } from "@/api/modules/examManage/examQuestion";
const questionTypeCnNo = ["一", "二", "三", "四", "五"];
const singleSelectionQuestionList: any = ref([]);
const moreSelectionQuestionList: any = ref([]);
const tfQuestionList: any = ref([]);
const completionQuestionList: any = ref([]);
const qaQuestionList: any = ref([]);
const tableLoaded: any = ref([]);

const questionList: any = ref([]);
const drawerVisible = ref(false);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const questionSelTable = ref();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  tableLoaded.value = true;
  return {
    list: data.dataList,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.isRandom = newParams.isRandom ? 1 : 0;
  return getExamQuestionSelList(newParams);
};

// 过滤选择项
const selectable = (row: any) => {
  return !row.isDefault;
};

// 表格配置项
const columns: ColumnProps<ExamQuestion.ResExamQuestionList>[] = [
  { type: "index", label: "序号", width: 80 },
  {
    prop: "questionStem",
    label: "题干名称",
    search: { el: "input" }
  },
  {
    prop: "questionType",
    label: "题型",
    enum: questionType,
    search: { el: "select" },
    render: scope => {
      let userTypeName = "";
      switch (scope.row.questionType) {
        case 1:
          userTypeName = "单选题";
          break;
        case 2:
          userTypeName = "多选题";
          break;
        case 3:
          userTypeName = "判断题";
          break;
        case 4:
          userTypeName = "填空题";
          break;
        case 5:
          userTypeName = "问答题";
          break;
        default:
          break;
      }
      return (
        <div>
          <span>{userTypeName}</span>
        </div>
      );
    },
    width: 100
  },
  {
    prop: "isRandom",
    label: "是否随机",
    search: { el: "switch" },
    isShow: false
  },
  {
    prop: "questionAnswer",
    label: "答案"
  },
  {
    prop: "questionScore",
    label: "分值",
    width: 60
  },
  { type: "selection", fixed: "right", width: 80, selectable }
];

const rules = reactive({
  paperName: [{ required: true, trigger: "blur", message: "请填写试卷" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<ExamPaper.ResExamPaperList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}
// 提交数据（新增/编辑）
const examPaperFormRef = ref<FormInstance>();

const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  if (drawerProps.value.isView) {
    tableLoaded.value = true;
  }
  resetQuestionList();
};

/**
 * 获取列表已选中数据
 */
const _getSelList = (values: any) => {
  singleSelectionQuestionList.value = [];
  moreSelectionQuestionList.value = [];
  tfQuestionList.value = [];
  completionQuestionList.value = [];
  qaQuestionList.value = [];
  console.log(values);
  values = values.map((item: any) => {
    console.log(item);
    return {
      questionId: item.questionId,
      questionStem: item.questionStem,
      questionScore: item.questionScore,
      questionType: item.questionType,
      optionList: item.optionList ?? []
    };
  });
  values.forEach((item: any) => {
    switch (item.questionType) {
      case 1:
        singleSelectionQuestionList.value.push(item);
        break;
      case 2:
        moreSelectionQuestionList.value.push(item);
        break;
      case 3:
        tfQuestionList.value.push(item);
        break;
      case 4:
        completionQuestionList.value.push(item);
        break;
      case 5:
        qaQuestionList.value.push(item);
        break;
      default:
        break;
    }
  });
};

/**
 * 清除试题
 */
const _clearQuestion = (questionType: number) => {
  const questionTypeMap = new Map([
    [1, "单选题"],
    [2, "多选题"],
    [3, "判断题"],
    [4, "填空题"],
    [5, "问答题"]
  ]);
  ElMessageBox.confirm(`确定清空${questionTypeMap.get(questionType)}`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    draggable: true,
    type: "warning"
  }).then(async () => {
    switch (questionType) {
      case 1:
        singleSelectionQuestionList.value = [];
        break;
      case 2:
        moreSelectionQuestionList.value = [];
        break;
      case 3:
        tfQuestionList.value = [];
        break;
      case 4:
        completionQuestionList.value = [];
        break;
      case 5:
        qaQuestionList.value = [];
        break;
      default:
        break;
    }
    setQuestionList();
  });
};

/**
 * 删除试题
 */
const _delQuestionItem = (questionType: number, index: number) => {
  ElMessageBox.confirm(`确定删除该试题`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    draggable: true,
    type: "warning"
  }).then(async () => {
    switch (questionType) {
      case 1:
        singleSelectionQuestionList.value.splice(index, 1);
        break;
      case 2:
        moreSelectionQuestionList.value.splice(index, 1);
        break;
      case 3:
        tfQuestionList.value.splice(index, 1);
        break;
      case 4:
        completionQuestionList.value.splice(index, 1);
        break;
      case 5:
        qaQuestionList.value.splice(index, 1);
        break;
    }
    setQuestionList();
  });
};

/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  examPaperFormRef.value && examPaperFormRef.value.resetFields();
  tableLoaded.value = false;
};

/**
 * 处理试题数据
 */
const setQuestionList = () => {
  const questionList = [
    ...(JSON.parse(JSON.stringify(singleSelectionQuestionList.value)) ?? []),
    ...(JSON.parse(JSON.stringify(moreSelectionQuestionList.value)) ?? []),
    ...(JSON.parse(JSON.stringify(tfQuestionList.value)) ?? []),
    ...(JSON.parse(JSON.stringify(qaQuestionList.value)) ?? []),
    ...(JSON.parse(JSON.stringify(completionQuestionList.value)) ?? [])
  ];
  questionSelTable.value.element.clearSelection();
  nextTick(() => {
    questionList.forEach((item: any) => {
      questionSelTable.value.tableData.forEach((row: any) => {
        if (row.questionId === item.questionId && row.questionStem === item.questionStem) {
          questionSelTable.value.element.toggleRowSelection(row, true);
        }
      });
    });
  });
};

/**
 * 重置试题
 */
const resetQuestionList = () => {
  singleSelectionQuestionList.value = [];
  moreSelectionQuestionList.value = [];
  tfQuestionList.value = [];
  completionQuestionList.value = [];
  qaQuestionList.value = [];
};
/**
 * 提交信息
 */
const handleSubmit = () => {
  examPaperFormRef.value!.validate(async valid => {
    if (!valid) return;
    let isReturn: boolean = false;

    singleSelectionQuestionList.value.forEach((item: any) => {
      if (isReturn) return false;
      if (!item.questionScore) {
        isReturn = true;
      }
    });

    moreSelectionQuestionList.value.forEach((item: any) => {
      if (isReturn) return false;
      if (!item.questionScore) {
        isReturn = true;
      }
    });

    tfQuestionList.value.forEach((item: any) => {
      if (isReturn) return false;
      if (!item.questionScore) {
        isReturn = true;
      }
    });

    completionQuestionList.value.forEach((item: any) => {
      if (isReturn) return false;
      if (!item.questionScore) {
        isReturn = true;
      }
    });

    qaQuestionList.value.forEach((item: any) => {
      if (isReturn) return false;
      if (!item.questionScore) {
        isReturn = true;
      }
    });

    if (isReturn) {
      ElMessage.error("请检查试题项子项,试题分数不能为空");
      return false;
    }
    const parmas: any = {};
    const filterFunc = (arr: any[]) => {
      return arr.map((item: any) => {
        return {
          questionId: item.questionId,
          questionScore: item.questionScore
        };
      });
    };
    singleSelectionQuestionList.value.length &&
      (parmas.singleSelectionQuestionList = filterFunc(singleSelectionQuestionList.value));
    moreSelectionQuestionList.value.length && (parmas.moreSelectionQuestionList = filterFunc(moreSelectionQuestionList.value));
    tfQuestionList.value.length && (parmas.tfQuestionList = filterFunc(tfQuestionList.value));
    completionQuestionList.value.length && (parmas.completionQuestionList = filterFunc(completionQuestionList.value));
    qaQuestionList.value.length && (parmas.qaQuestionList = filterFunc(qaQuestionList.value));
    if (JSON.stringify(parmas) === "{}") {
      ElMessage.error("请先同步试题");
      return false;
    }
    try {
      await drawerProps.value.api!({ ...drawerProps.value.row, ...parmas });
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
      tableLoaded.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
watch(
  () => tableLoaded.value,
  async (newVal: any) => {
    if (newVal) {
      if (drawerProps.value.title !== "新增") {
        try {
          const { result } = (await getExamPaperDtl({ paperId: drawerProps.value.row!.paperId as number })) as ResultData;

          function getQuestionList() {
            const {
              singleSelectionQuestionList,
              moreSelectionQuestionList,
              tfQuestionList,
              qaQuestionList,
              completionQuestionList
            } = result;
            questionList.value = [
              { label: "单选题", value: singleSelectionQuestionList },
              { label: "多选题", value: moreSelectionQuestionList },
              { label: "判断题", value: tfQuestionList },
              { label: "填空题", value: completionQuestionList },
              { label: "问答题", value: qaQuestionList }
            ].filter((item: any) => {
              return item.value;
            });
            return [
              ...(singleSelectionQuestionList ?? []),
              ...(moreSelectionQuestionList ?? []),
              ...(tfQuestionList ?? []),
              ...(qaQuestionList ?? []),
              ...(completionQuestionList ?? [])
            ];
          }
          if (drawerProps.value.title === "编辑") {
            nextTick(() => {
              console.log(getQuestionList());
              getQuestionList().forEach((item: any) => {
                switch (item.questionType) {
                  case 1:
                    singleSelectionQuestionList.value.push(item);
                    break;
                  case 2:
                    moreSelectionQuestionList.value.push(item);
                    break;
                  case 3:
                    tfQuestionList.value.push(item);
                    break;
                  case 4:
                    completionQuestionList.value.push(item);
                    break;
                  case 5:
                    qaQuestionList.value.push(item);
                    break;
                  default:
                    break;
                }
                questionSelTable.value.tableData.forEach((row: any) => {
                  if (row.questionId === item.questionId && row.questionStem === item.questionStem) {
                    questionSelTable.value.element.toggleRowSelection(row, true);
                  }
                });
              });
              setQuestionList();
            });
          } else {
            getQuestionList();
          }
        } catch (error) {}
      }
    }
  }
);

defineExpose({
  acceptParams
});
</script>

<style lang="scss" scoped>
.header {
  padding-bottom: 30px;
  border-bottom: 1px solid #eeeeee;
  .countdownTime {
    padding: 10px;
    font-family: "仿宋";
    font-size: 18px;
    font-weight: 600;
    color: #ff0000;
    text-align: right;
  }
  .examTitle {
    padding: 10px 0 30px;
    font-size: 22px;
    font-weight: 700;
    text-align: center;
  }
  .examSubTitle {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 100%;
    margin: 0 auto;
    font-size: 16px;
    font-weight: 500;
    .examSubTitle__item {
      display: flex;
      justify-content: center;
      .examSubTitle__item__text {
        padding: 0 10px;
        text-decoration: underline;
        text-underline-offset: 2px;
      }
    }
  }
}
.testPart {
  width: 80%;
  min-width: 1000px;
  padding: 30px 0;
  margin: 30px auto;
  background: var(--el-color-primary-light-9);
  .testPart__title {
    padding: 0 30px;
    margin-bottom: 30px;
    font-size: 16px;
    font-weight: 600;
    line-height: 40px;
    color: var(--el-color-primary);
  }
  .testPaper {
    padding: 0 50px;
    background: var(--el-color-primary-light-9);
    .testList {
      padding: 20px 0 0;
      .testTypeTitle {
        padding: 0 0 20px;
      }
      .testItem {
        margin-bottom: 10px 0;
        &:last-child {
          margin-bottom: 0;
        }
        .answerContent {
          padding: 10px 20px;
          margin: 0 10px;
          .checkBox {
            display: inline-block;
            width: 14px;
            height: 14px;
            margin-right: 10px;
            vertical-align: bottom;
            border: 1px solid #666666;
          }
        }
        .answerContent1 {
          height: 40px;
          padding: 20px 0 0;
        }
        .answerContent2 {
          height: 160px;
          padding: 20px 0 0;
        }
      }
    }
  }
}
.content {
  display: flex;
  justify-content: space-between;
  height: 100%;
  .questionSelList,
  .paperForm {
    box-sizing: border-box;
    flex: 2;
    height: 100%;
    padding-right: 20px;
    overflow-y: auto;
  }
  .splitLine {
    width: 1px;
    height: 100%;
    margin-right: 30px;
    margin-left: 10px;
    background: #eeeeee;
  }
  .questionSelList {
    flex: 3;
    height: 100%;
    overflow-y: auto;
  }
}
.questionItem {
  display: flex;
  align-items: center;

  // justify-content: space-between;
  padding: 5px 0 5px 20px;
  .questionNo {
    width: 20px;
    margin-right: 10px;
    font-size: 14px;
    color: #666666;
  }
  .questionName {
    width: 360px;
    margin-right: 10px;
    overflow: hidden;
    font-size: 14px;
    color: #666666;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .questionScore {
    width: 60px;
    margin-right: 10px;
    text-align: center;
  }
}
.answerOpts {
  padding: 5px 0 5px 50px;
}
.answerItem {
  padding: 5px 0;
  overflow: hidden;
  font-size: 14px;
  color: #666666;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.questionTitle {
  display: flex;
  justify-content: space-between;
  padding: 20px 0 20px 20px;
  font-size: 14px;
  font-weight: 600;
  color: #666666;
}
.delBtn {
  cursor: pointer;
}
.clearBtn {
  margin-left: 20px;
  color: var(--el-color-error);
  text-decoration: underline;
  text-underline-offset: 2px;
  cursor: pointer;
}
</style>

<style media="print">
@page {
  size: auto; /* auto is the initial value */
  margin: 3mm; /* this affects the margin in the printer settings */
}
html {
  margin: 0; /* this affects the margin on the html before sending to printer */
  background-color: #ffffff;
}
body {
  margin: 10mm 0; /* margin you want for the content */
}
</style>
